<template>
  <div>
    <fullscreenModal
      :modal="showModal"
      :label="'我的购物车'"
      :isShowEdit="false"
      :showSave="false"
      editType="other"
      @handleClose="handleClose()"
    >
      <p class="myBtn">
        <van-icon name="replay" @click="getCarData()" />
      </p>
      <div class="orderContent">
        <div v-for="(item, index) in dataList" :key="index" class="list-item">
          <div class="head">
            <van-checkbox :value="item.ischeck" @click="checkshop(index)">
              <div class="flexRow head-item">
                <p>
                  {{ item.networkName }}
                </p>
              </div>
            </van-checkbox>
          </div>
          <div
            class="flexRow"
            style="margin-top: 10px"
            v-for="(val, i) in item.shoppingCartGoodsVOS"
            :key="i"
          >
            <van-checkbox
              style="margin-right: 10px"
              :value="val.ischeck"
              :disabled="
                val.salesStatus !== '1' ||
                val.stockNum == 0 ||
                val.volume == 0 ||
                val.ableStatus == '0'
              "
              @click="checkgoods(index, i, val)"
            ></van-checkbox>
            <a class="van-card__thumb">
              <div
                class="van-image"
                style="width: 100%; height: 100%; position: relative"
              >
                <img
                  v-if="val.salesStatus !== '1'"
                  class="bgImg"
                  src="../../../../assets/images/offShlf.png"
                  alt=""
                />
                <img
                  class="van-image__img"
                  style="object-fit: cover"
                  :src="
                    fileUrlObj[val.goodsMainFileCode] ||
                    (loading ? 'loading.gif' : 'noImgData.png')
                  "
                />
              </div>
            </a>
            <div class="van-card__content">
              <p
                class="van-card__title van-multi-ellipsis--l2"
                style="font-size: 14px"
              >
                {{ val.goodsName }}
              </p>

              <div class="priceNum">
                <p style="flex: 1">{{ val.attrNames }}</p>
                <p v-if="val.limitBuyAmount !== 0">
                  限购：{{ val.limitBuyAmount }}
                </p>
              </div>

              <div class="van-card__bottom">
                <div class="van-card__price">
                  <div>
                    <span
                      style="color: #e1251b"
                      class="van-card__price-currency"
                      >¥</span
                    ><span class="van-card__price-integer price">{{
                      val.addSellingPrice
                    }}</span>
                  </div>
                </div>
                <div class="van-card__num">
                  <van-stepper
                    v-model="val.addAmount"
                    class="stepBox"
                    integer
                    min="1"
                    :max="
                      val.limitBuyAmount
                        ? Math.min(val.stockNum, val.limitBuyAmount)
                        : val.stockNum
                    "
                    :disabled="
                      val.salesStatus !== '1' ||
                      val.stockNum == 0 ||
                      val.volume == 0 ||
                      val.ableStatus == '0'
                    "
                    @change="changeNumber(val)"
                  />
                </div>
              </div>
              <div class="btnRight">
                <van-button
                  round
                  plain
                  hairline
                  type="success"
                  size="mini"
                  @click="handleDelete(val)"
                  ><span style="padding: 5px">删除</span></van-button
                >
              </div>
            </div>

            <div class="con"></div>
          </div>
        </div>
        <van-empty
          v-if="!spinLoading && !dataList.length"
          class="custom-image"
          :image="require('../../../../assets/images/empty.png')"
          description="暂无数据"
        />
        <div class="bottomTip">
          <van-submit-bar
            :price="totalPrice * 100"
            :suffix-label="'(已选' + selectedNum + '件)'"
            button-text="结算"
            :disabled="!dataList.length"
            @submit="handlePayment"
          >
            <van-checkbox
              v-model="checkAll"
              @click="handleCheckAll"
              :disabled="!dataList.length"
              >全选</van-checkbox
            >
          </van-submit-bar>
        </div>
      </div>
    </fullscreenModal>
    <full-loading v-if="spinLoading"></full-loading>
    <detail ref="orderRef" @refresh="getCarData"></detail>
  </div>
</template>

<script>
import { queryFileList } from "@/api/common";
import detail from "../goodsList/order";
import {
  queryCartList,
  editCart,
  delCart,
} from "@/api/srvAssurance/shoppingMall/markeApi";
export default {
  components: { detail },
  data() {
    return {
      showModal: false,
      showPayModal: false,
      spinLoading: false,
      loading: false,
      dataList: [],
      checkAllGroup: [],
      selectedData: [],
      checkAll: false,
      fileUrlObj: {},
    };
  },
  computed: {
    // 计算总价
    totalPrice() {
      let price = 0;
      this.dataList.forEach((item) => {
        item.shoppingCartGoodsVOS.forEach((val) => {
          if (val.ischeck) {
            price += val.sellingPrice * val.addAmount;
          }
        });
      });
      return price.toFixed(2);
    },
    // 统计勾选商品
    selectedNum() {
      let number = 0;
      this.dataList.forEach((item) => {
        item.shoppingCartGoodsVOS.forEach((goodsitem) => {
          if (goodsitem.ischeck) {
            goodsitem.networkName = item.networkName;
            goodsitem.url = this.fileUrlObj[goodsitem.goodsMainFileCode];
            this.selectedData.push(goodsitem);
            number += goodsitem.addAmount;
          }
        });
      });
      return number;
    },
  },
  methods: {
    openMyCar() {
      this.showModal = true;
      this.getCarData();
    },
    handleClose() {
      this.showModal = false;
      this.$emit("refresh");
    },
    // 查询购物车列表
    getCarData() {
      this.totalPrice = 0;
      let filecodeArr = [];
      this.checkAll = false;
      this.spinLoading = true;
      this.dataList = [];
      this.selectedData = [];
      queryCartList()
        .then((res) => {
          if (res.code === 1000 && res.data) {
            res.data.forEach((item) => {
              item.ischeck = false;
              item.shoppingCartGoodsVOS.forEach((val) => {
                val.ischeck = false;
                val.networkId = item.networkId;
                if (
                  val.goodsMainFileCode &&
                  !this.fileUrlObj[val.goodsMainFileCode]
                ) {
                  filecodeArr.push(val.goodsMainFileCode);
                  this.fileUrlObj[val.goodsMainFileCode] = "";
                }

                var dateEnd = new Date().format("yyyy-MM-dd hh:mm:ss"); //获取当前时间
                if (
                  val.seckillStartTime != null &&
                  dateEnd < val.seckillStartTime
                ) {
                  val.volume = 0;
                }

                if (
                  val.seckillStartTime != null &&
                  val.seckillEndTime != null
                ) {
                  if (
                    dateEnd < val.seckillStartTime ||
                    dateEnd > val.seckillEndTime
                  ) {
                    val.volume = 0;
                  }
                }
              });
            });
            this.dataList = res.data;
            if (filecodeArr.length) {
              this.queryFileInfoData(filecodeArr);
            }
          }
          setTimeout(() => {
            this.spinLoading = false;
          }, 400);
        })
        .catch(() => {
          this.spinLoading = false;
        });
    },
    // 改变数量
    changeNumber(val) {
      let item = {
        cartId: val.cartId,
        addAmount: val.addAmount,
      };
      editCart(item).then((res) => {
        if (res.code == 1000) {
        }
      });
    },
    // 商店勾选
    checkshop(shopindex) {
      this.dataList[shopindex].ischeck = !this.dataList[shopindex].ischeck;
      if (this.dataList[shopindex].ischeck) {
        this.dataList[shopindex].shoppingCartGoodsVOS.forEach((item) => {
          if (
            item.salesStatus == "1" &&
            item.stockNum != 0 &&
            item.volume != 0 &&
            item.ableStatus != "0"
          ) {
            item.ischeck = true;
          }
        });
      } else {
        this.dataList[shopindex].shoppingCartGoodsVOS.forEach((item) => {
          item.ischeck = false;
        });
      }

      let length = 0;

      this.dataList.forEach((item) => {
        if (item.ischeck) {
          length++;
        }
      });

      if (length === this.dataList.length) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }
    },
    // 单商品勾选
    checkgoods(shopindex, goodsindex, val) {
      let length = 0;
      let length2 = 0;

      if (
        val.salesStatus == "1" &&
        val.stockNum != 0 &&
        val.volume != 0 &&
        val.ableStatus != "0"
      ) {
        this.dataList[shopindex].shoppingCartGoodsVOS[goodsindex].ischeck =
          !this.dataList[shopindex].shoppingCartGoodsVOS[goodsindex].ischeck;

        this.dataList[shopindex].shoppingCartGoodsVOS.forEach((item) => {
          if (item.ischeck) {
            length++;
          }
        });
        if (this.dataList[shopindex].shoppingCartGoodsVOS.length == length) {
          this.dataList[shopindex].ischeck = true;
        } else {
          this.dataList[shopindex].ischeck = false;
        }

        this.dataList.forEach((item) => {
          if (item.ischeck) {
            length2++;
          }
        });
        if (this.dataList.length === length2) {
          this.checkAll = true;
        } else {
          this.checkAll = false;
        }
      }
    },
    // 全选
    handleCheckAll() {
      if (this.checkAll) {
        this.dataList.forEach((item) => {
          item.ischeck = true;
          item.shoppingCartGoodsVOS.forEach((goodsitem) => {
            if (
              goodsitem.salesStatus == "1" &&
              goodsitem.stockNum != 0 &&
              goodsitem.volume != 0 &&
              goodsitem.ableStatus != "0"
            ) {
              goodsitem.ischeck = true;
            }
          });
        });
      } else {
        this.dataList.forEach((item) => {
          item.ischeck = false;
          item.shoppingCartGoodsVOS.forEach((goodsitem) => {
            goodsitem.ischeck = false;
          });
        });
      }
    },
    // 结算
    handlePayment() {
      if (this.selectedData.length == 0) {
        this.$Notify({
          type: "warning",
          message: "请选择购买的商品",
        });
        return;
      }
      let cartIdArr = [];
      this.dataList.forEach((item) => {
        cartIdArr.push({
          networkId: item.networkId,
          networkName: item.networkName,
          total: this.selectedNum,
          allprice: this.totalPrice,
          newArr: [],
        });
      });

      var isDefault = false;
      this.selectedData.forEach((val, i) => {
        if (!val.addAmount) {
          isDefault = true;
          this.$Notify({
            type: "warning",
            message: "选中的商品数量不能为空！",
          });
          return;
        }
        cartIdArr.forEach((item, i) => {
          if (item.networkId == val.networkId) {
            item.newArr.push(val);
          }
        });
      });

      if (!isDefault) {
        cartIdArr.forEach((item, i) => {
          if (item.newArr.length == 0) {
            delete cartIdArr[i];
          }
          item.newArr = [...new Set(item.newArr)];
          item.newArr.forEach((val) => {
            val.buyCount = val.addAmount;
            val.imgUrl = val.url;
          });
        });
        let arr1 = cartIdArr.filter((d) => d);
        this.$refs.orderRef.resetForm();
        this.$refs.orderRef.openMyCar(arr1);
      }
    },
    // 删除
    handleDelete(item) {
      this.$Dialog
        .confirm({
          title: "是否确定删除购物车该商品？",
        })
        .then(() => {
          this.spinLoading = true;
          delCart([item.cartId])
            .then((res) => {
              this.spinLoading = false;
              if (res.code === 1000) {
                this.$Notify({ type: "success", message: "删除成功！" });
                this.getCarData();
              }
            })
            .catch(() => {
              this.spinLoading = false;
            });
        })
        .catch(() => {});
    },
    // 获取图片信息
    queryFileInfoData(filecodeArr) {
      this.loading = true;
      queryFileList(filecodeArr)
        .then((res) => {
          if (res.code === 1000 && res.data) {
            res.data.forEach((item) => {
              this.fileUrlObj[item.fileCode] = item.url;
            });
            this.$forceUpdate();
            this.loading = false;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style scoped lang="less">
.myBtn {
  position: absolute;
  right: 15px;
  top: 12px;
  font-size: 18px;
}
/deep/.stepBox {
  .van-stepper__input {
    width: 60px;
  }
  .van-stepper__minus,
  .van-stepper__plus,
  .van-stepper__input {
    height: 23px;
    line-height: 23px;
    font-size: 12px;
  }
}
.orderContent {
  padding: 8px;
  height: calc(100% - 46px);
  box-sizing: border-box;
  overflow: auto;
  background: #eee;
  .list-item {
    background: #fff;
    padding: 8px;
    margin-top: 8px;
    box-sizing: border-box;
    border-radius: 10px;
  }
  .list-head {
    margin-top: 8px;
  }
  .flexRow {
    display: flex;
    align-items: center;
    img {
      width: 100%;
      height: 100%;
    }
    .bgImg {
      position: absolute;
      top: -15px;
      left: -16px;
      width: 120px;
      height: 120px;
    }
  }
  .price {
    color: #e1251b;
    font-size: 18px;
    margin-left: 5px;
  }

  .priceNum {
    color: #aaa;
    font-size: 11px;
    padding: 5px 0;
    display: flex;
  }

  .head {
    font-size: 12px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    p {
      flex: 1;
      //   margin-top: 5px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 200px;
    }
    span {
      margin-left: 10px;
    }
  }
  .dishName {
    p {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    span {
      color: #20bc12;
      font-size: 12px;
      margin-left: 10px;
    }
    .other {
      color: rgb(242, 36, 36);
    }
  }
}
.bottomTip {
  .van-submit-bar__suffix-label {
    font-size: 11px;
    color: #aaa;
    float: left;
    line-height: 28px;
  }
  .van-submit-bar__button {
    width: auto;
  }
}
</style>
